package chances.epg.navigator.history;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

public class UserAccessEntry implements java.io.Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -1859694744785713296L;
	
	private String path;
	private Map<String ,String> params;
	
	
	
	public String getPath() {
		return path;
	}

	public Map<String, String> getParams() {
		return params;
	}

	
	public UserAccessEntry(String path , Map<String ,String> params){
		this.path = path;
		this.params = new HashMap<String,String>();
		if(params!=null){
			this.params.putAll(params);
		}
	}
	


	public String getFullPath(){
		return genURL(this.path,this.params);
	}
	
	public String getFullPath(String append){
		String url = genURL(this.path,this.params);
		if(url.indexOf('?')>0){
			return url+"&"+append;
		}else{
			return url +"?"+append;
		}
	}
	

	/**
	 * 生成URL
	 * @param url
	 * @param params
	 * @return
	 */
	
	public static String genURL(String url,Map params){
			String result = url;
			if(params==null || params.isEmpty()){
			   return result;
		    }   	
			String queryStr =genQueryString(params);
			if(StringUtils.isNotEmpty(queryStr)){
				if(url.indexOf("?")>0){
					result= result +"&"+queryStr;
				}else{
					result= result +"?"+queryStr;
				}
			}
			return result;
	}
	/**
	 * 生成一个QueryString;
	 * @param map
	 * @return
	 */
	public static String genQueryString(Map map){
		 Set<Map.Entry> keyValues = map.entrySet();
		 StringBuffer buffer = new StringBuffer();
		   for(Iterator iter = keyValues.iterator();iter.hasNext();){
			  Map.Entry entry = (Entry) iter.next();
			  String key = (String)entry.getKey(); 
			  buffer.append(key).append("=").append(entry.getValue());
			  if(iter.hasNext()){
				  buffer.append("&");
			  }
		   }
	  	  return buffer.toString();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof String){
			return this.path.equals(obj);
		}else if(obj instanceof UserAccessEntry){
			return this.path.equals(((UserAccessEntry) obj).path);
		}else{
			return false;
		}
	}

	public static UserAccessEntry parseUrl(String returnUrl) {
		return new UserAccessEntry(returnUrl,null);
	}

	public void addParam(String name, String focusId) {
		this.params.put(name, focusId);
		
	}
	
}
